package com.baitiaojun.common.utils.spring;

import cn.hutool.core.util.ObjectUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class SpringUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtils.applicationContext = applicationContext;
    }

    public static <T> T getBean(Class<T> beanType) {
        if (ObjectUtil.isNull(beanType)) {
            return null;
        }
        return applicationContext.getBean(beanType);
    }

    public static Object getBean(String beanName) {
        if (StringUtils.isBlank(beanName)) {
            return null;
        }
        return applicationContext.getBean(beanName);
    }

    public static <T> T getBean(String beanName, Class<T> beanType) {
        if (StringUtils.isBlank(beanName) && ObjectUtil.isNotNull(beanType)) {
            return null;
        }
        return applicationContext.getBean(beanName, beanType);
    }

    public static boolean isContains(String beanName) {
        if (StringUtils.isBlank(beanName)) {
            return false;
        }
        return applicationContext.containsBean(beanName);
    }

    public static boolean isSingleton(String beanName) {
        if (StringUtils.isBlank(beanName)) {
            return false;
        }
        return applicationContext.isSingleton(beanName);
    }

    public static Class<?> getBeanType(String beanName) {
        if (StringUtils.isBlank(beanName)) {
            return null;
        }
        return applicationContext.getType(beanName);
    }

    public static String[] getAliases(String beanName) {
        if (StringUtils.isBlank(beanName)) {
            return new String[0];
        }
        return applicationContext.getAliases(beanName);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getProxy(T invoker) {
        return (T) AopContext.currentProxy();
    }

    public static String[] getActiveProfiles() {
        return getEnvironment().getActiveProfiles();
    }

    public static <T> T getProperty(String key, Class<T> type) {
        return getEnvironment().getProperty(key, type);
    }

    public static Environment getEnvironment() {
        return applicationContext.getEnvironment();
    }
}
